package jedis;

import redis.clients.jedis.*;

import java.util.*;

/**
 * jedis客户端分片操作
 */
public class ShardOperation {
    public static void main(String[] args) {
        setOperation();
        getOperation();

    }



    private static ShardedJedisPool getPool(){

        /**
         *
         */
        JedisPoolConfig config = new JedisPoolConfig();
        config.setTestOnBorrow(true);
        List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>();
        JedisShardInfo infoA = new JedisShardInfo("192.168.10.100", 6379);
        infoA.setPassword("Bocon123456*");
        JedisShardInfo infoB = new JedisShardInfo("192.168.10.93", 6379);
        infoB.setPassword("redis");
        jedisShardInfoList.add(infoA); jedisShardInfoList.add(infoB);
        ShardedJedisPool sharedPool = new ShardedJedisPool(config, jedisShardInfoList);
        return sharedPool;
    }

    private static void setOperation(){

        ShardedJedisPool sharedPool = getPool();

        try{

            for(int i=0; i<50; i++){
                String key = "test" + i;
                ShardedJedis client = sharedPool.getResource();
                System.out.println(client.getShard(key).getClient().getHost()+": "+client.getShard(key).getClient().getPort());
                System.out.println(client.set(key, "第"+(i+1)+"项"));
                client.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void getOperation(){

        ShardedJedisPool sharedPool = getPool();

        try{

            for(int i=0; i<50; i++){
                String key = "test" + i;
                ShardedJedis client = sharedPool.getResource();
                System.out.println(client.getShard(key).getClient().getHost()+": "+client.getShard(key).getClient().getPort());
                System.out.println(client.get(key));
                client.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

















